package com.example.demo.system.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.FileUpReturnEntity;
import com.example.demo.entity.base.PageRequestBean;
import com.example.demo.entity.base.PageResponseBean;
import com.example.demo.entity.base.ResponseEntity;
import com.example.demo.entity.mybatisplus.SysConfigEntity;
import com.example.demo.file.FileManager;
import com.example.demo.file.FileManagerFactory;
import com.example.demo.system.dao.SystemConfigDao;
import com.example.demo.system.service.SystemConfigService;
import com.example.demo.util.CommonUtil;
import com.example.demo.util.EmptyUtil;
import com.example.demo.util.PropertiesUtil;
import com.example.demo.util.ResponseFactory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigDao, SysConfigEntity> implements SystemConfigService{
	
	@Autowired
	private Environment env;

	@Override
	public ResponseEntity<String> addSysConfig(SysConfigEntity sysConf, MultipartFile file) {

		//type为2表示此属性为图片类
		if("2".equals(sysConf.getConf_type())) {
			try {
//				String conf_value = FileUtils.uploadFileInServer(file, env.getProperty("server.servlet.context-path"));
				
				/*InputStream fileStream = file.getInputStream();
				
				String fileName = file.getOriginalFilename();
				
				String fileFormat = fileName.substring(fileName.lastIndexOf("."));
				
				OSSResultEntity ossRet = OSSUtils.uploadFile(fileStream, "sysconfig", fileFormat);*/
				
				FileManager fileManager = FileManagerFactory.build(PropertiesUtil.getProperty("fileSaveType"));
				FileUpReturnEntity upRet = fileManager.uploadSingleFile(file, "sysconfig", false, false);
				
				String conf_value = upRet.getFileUrl();
				String img_save_type = upRet.getSaveType();
				
				sysConf.setConf_value(conf_value);
				sysConf.setImg_save_type(img_save_type);
			} catch (Exception e) {
				log.error("上传图片至服务器失败",e);
				return ResponseFactory.setFail("上传图片至服务器失败");
			}
		}
		
		String conf_key = sysConf.getConf_key();
		
		if(EmptyUtil.isEmpty(conf_key)) {
			return ResponseFactory.setFail("未填写属性键值");
		}
		
		Map<String, Object> param = new HashMap<>();
		param.put("conf_key", conf_key);
		
		List<SysConfigEntity> oldConfigs = baseMapper.selectByMap(param);
		
		if(EmptyUtil.isNotEmpty(oldConfigs)) {
			return ResponseFactory.setFail("已存在相同的键值,请重新输入键值");
		}
		
		Date nowtime = new Date();
		
		sysConf.setCreate_time(nowtime);
		sysConf.setUpdate_time(nowtime);
		
		try {
			baseMapper.insert(sysConf);
		} catch (Exception e) {
			log.error("保存系统常用属性失败",e);
			return ResponseFactory.setFail("保存系统常用属性失败");
		}
		
		return ResponseFactory.setSuccess("保存系统常用属性成功");
	}

	@Override
	public ResponseEntity<String> deleteSysConfigs(String key_ids) {

		String[] keyArr = key_ids.split(",");
		
		List<String> keys = Arrays.asList(keyArr);
		
		try {
			baseMapper.deleteBatchIds(keys);
		} catch (Exception e) {
			log.error("删除系统常用属性失败",e);
			return ResponseFactory.setFail("删除系统常用属性失败");
		}
		
		return ResponseFactory.setSuccess("删除系统常用属性成功");
	}

	@Override
	public ResponseEntity<String> updateSysConfig(SysConfigEntity sysConf, MultipartFile file) {
		
		if(EmptyUtil.isEmpty(sysConf.getKey_id())) {
			return ResponseFactory.setFail("未传入属性id");
		}
		
		//type为2表示此属性为图片类
		if("2".equals(sysConf.getConf_type())&&null!=file) {
			try {
				/*String conf_value = FileUtils.uploadFileInServer(file, env.getProperty("server.servlet.context-path"));
				sysConf.setConf_value(conf_value);*/
				FileManager fileManager = FileManagerFactory.build(PropertiesUtil.getProperty("fileSaveType"));
				FileUpReturnEntity upRet = fileManager.uploadSingleFile(file, "sysconfig", false, false);
				
				String conf_value = upRet.getFileUrl();
				String img_save_type = upRet.getSaveType();
				
				sysConf.setConf_value(conf_value);
				sysConf.setImg_save_type(img_save_type);
			} catch (Exception e) {
				log.error("上传图片至服务器失败",e);
				return ResponseFactory.setFail("上传图片至服务器失败");
			}
		}
		
		sysConf.setUpdate_time(new Date());
		
		try {
			baseMapper.updateById(sysConf);
		} catch (Exception e) {
			log.error("修改系统常用属性失败",e);
			return ResponseFactory.setFail("修改系统常用属性失败");
		}
		
		return ResponseFactory.setSuccess("修改系统常用属性成功");
	}

	@Override
	public ResponseEntity<PageResponseBean<SysConfigEntity>> querySysConfigForPage(
			PageRequestBean<SysConfigEntity> pagerequest) {
		
		int pageNum = pagerequest.getPageNum();
		
		int pageSize = pagerequest.getPageSize();
		
		SysConfigEntity params = pagerequest.getParams();
		
		if(null == params) {
			params = new SysConfigEntity();
		}
		
		Page<SysConfigEntity> page = PageHelper.startPage(pageNum, pageSize, true);
		
		List<SysConfigEntity> sysConfigs = null;
		
		try {
			sysConfigs = baseMapper.querySysConfigList(params);
		} catch (Exception e) {
			log.error("分页查询系统常用属性失败",e);
			return ResponseFactory.setFail("分页查询系统常用属性失败");
		}
		

		long total = page.getTotal();

		int totalPages;

		try {
			totalPages = CommonUtil.getTotalPages(pageSize, total);
		} catch (Exception e) {
			log.error("获取总页数时失败", e);
			return ResponseFactory.setFail("获取总页数时失败");
		}
		
		PageResponseBean<SysConfigEntity> pageresponse = new PageResponseBean<>(total, pageSize, pageNum
																				, totalPages, sysConfigs);
		
		return ResponseFactory.setObject(pageresponse);
	}
}
